package com.heima.serach.listen;

import com.heima.common.constants.message.NewsUpOrDownConstants;
import com.heima.es.service.EsService;
import com.heima.feigns.ArticelFeifn;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.serach.vos.SearchArticleVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
@Slf4j
public class ArticleAddOrRemoveListener {

    @Autowired
    ArticelFeifn articelFeifn;
    @Autowired
    EsService<SearchArticleVO>esService;

    @RabbitListener(queuesToDeclare = @Queue(value = NewsUpOrDownConstants.NEWS_UP_FOR_ES_QUEUE))
    public void handleup(String articleId){
        log.info("搜索微服务 接收到添加文章到索引库消息==> {}",articleId);

        ResponseResult<SearchArticleVO> articleResult = articelFeifn.findArticle(Long.valueOf(articleId));
        if (!articleResult.checkCode()){
            log.error("索引库添加失败 远程调用文章信息失败   文章id: {}",articleId);
        }
        SearchArticleVO searchArticleVo = articleResult.getData();

        if(searchArticleVo == null){
            log.error("索引库添加失败 未获取到对应文章信息   文章id: {}",articleId);
        }

        try {
            esService.save(searchArticleVo,"app_info_article");
            log.info("成功更新索引信息   add: {}",articleId);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("消息消费确认失败   文章id: {}  原因: {}",articleId,e.getMessage());
        }
    }


    @RabbitListener(queuesToDeclare = @Queue(value = NewsUpOrDownConstants.NEWS_DOWN_FOR_ES_QUEUE))
    public void handledown(String articleId){
        log.info("搜索微服务 接收到删除文章到索引库消息==> {}",articleId);
        esService.deleteById(articleId,"app_info_article");
        log.info("删除索引信息成功");
    }

}